<template>
  <div style="position: fixed;right: 15px;bottom: 30px;z-index: 999">
    <!-- 回顶部按钮为一张50*50的图片 -->
    <!-- btnFlag 控制图片显示隐藏 -->
    <!-- backTop 回顶部的方法 -->
    <img v-if="btnFlag" class="go-top" src="/static/images/back_top.png" style="cursor: pointer;" title="返回顶部" @click="backTop">
  </div>
</template>

<script>

  export default {
    name: 'content-top',
    props: {
    },
    data() {
      return {
        btnFlag:false,
        scrollTop:1
      }
    },
    methods: {
      // 点击图片回到顶部方法，加计时器是为了过渡顺滑
      backTop() {
        const that = this;
        let timer = setInterval(() => {
          let ispeed = Math.floor(-that.scrollTop / 5);
          document.documentElement.scrollTop = document.body.scrollTop = that.scrollTop + ispeed;
          if (that.scrollTop === 0) {
            clearInterval(timer)
          }
        }, 16)
      },
      // 为了计算距离顶部的高度，当高度大于60显示回顶部图标，小于60则隐藏
      scrollToTop() {
        const that = this;
        let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
        that.scrollTop = scrollTop;
      }
    },
    mounted() {
      window.addEventListener('scroll', this.scrollToTop);
    },
    destroyed() {
      window.removeEventListener('scroll', this.scrollToTop)
    },
    created() {

    },
    watch: {
      scrollTop(val) {
        if (this.scrollTop > 100) {
          this.btnFlag = true;
        } else {
          this.btnFlag = false;
        }
      }
    }
  }
</script>
